package com.ensa.googlemapsandroidv2;

import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.ensa.googlemapsandroidv2.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class localisationmalade extends FragmentActivity implements
		ConnectionCallbacks, OnConnectionFailedListener, LocationListener,
		OnMyLocationButtonClickListener, LocationSource {

	// private MapView mapview;
	private GoogleMap mMap;

	private LocationClient mLocationClient;

	final int RQS = 1;

	// These settings are the same as the settings for the map. They will in
	// fact give you updates
	// at the maximal rates currently possible.
	private static final LocationRequest REQUEST = LocationRequest.create()
			.setInterval(5000) // 5 seconds
			.setFastestInterval(16) // 16ms = 60fps
			.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.localisationmalade);
	}

	@Override
	protected void onResume() {
		super.onResume();
		setUpMapIfNeeded();
		setUpLocationClientIfNeeded();
		mLocationClient.connect();
	}

	@Override
	public void onPause() {
		super.onPause();
		if (mLocationClient != null) {
			mLocationClient.disconnect();
		}
	}

	private void setUpMapIfNeeded() {
		// Do a null check to confirm that we have not already instantiated the
		// map.
		if (mMap == null) {
			// Try to obtain the map from the SupportMapFragment.
			mMap = ((SupportMapFragment) getSupportFragmentManager()
					.findFragmentById(R.id.map)).getMap();

			// LatLng loc= new LatLng(
			// mLocationClient.getLastLocation().getLatitude(),
			// mLocationClient.getLastLocation().getLongitude());
			// CameraPosition cam = new
			// CameraPosition.Builder().target(loc).zoom(14).bearing(90).tilt(30).build();

			// mMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
			// Check if we were successful in obtaining the map.
			if (mMap != null) {

				mMap.setMyLocationEnabled(true);
				mMap.setOnMyLocationButtonClickListener(this);
			}

		}
	}

	private void setUpLocationClientIfNeeded() {
		if (mLocationClient == null) {
			mLocationClient = new LocationClient(getApplicationContext(), this, // ConnectionCallbacks
					this); // OnConnectionFailedListener
		}

	}

	/**
	 * Button to get current Location. This demonstrates how to get the current
	 * Location as required without needing to register a LocationListener.
	 */
	public void showMyLocation(View view) {
	}

	/**
	 * Implementation of {@link LocationListener}.
	 */

	@Override
	public void onLocationChanged(Location location) {
	}

	/**
	 * Callback called when connected to GCore. Implementation of
	 * {@link ConnectionCallbacks}.
	 */
	@Override
	public void onConnected(Bundle connectionHint) {

		mLocationClient.requestLocationUpdates(REQUEST, this); // LocationListener
		try {
			//Thread.sleep(10000);
			//Log.i("fff", mLocationClient.getLastLocation().getLatitude() + "");
			Marker me = mMap.addMarker(new MarkerOptions()
            .position(new LatLng(
					mLocationClient.getLastLocation().getLatitude(),mLocationClient.getLastLocation().getLongitude()))
            .title("meee")
            .snippet("Population: 4,137,400")
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.image1)));
			
			mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
					mLocationClient.getLastLocation().getLatitude(),
					mLocationClient.getLastLocation().getLongitude()), 13));

			/*try {
				HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
				@Override
				public void initialize(HttpRequest request) {
				request.setParser(new JsonObjectParser(JSON_FACTORY));
				}
				});

				GenericUrl url = new GenericUrl("http://maps.googleapis.com/maps/api/directions/json");
				url.put("origin", "Chicago,IL");
				url.put("destination", "Los Angeles,CA");
				url.put("sensor",false);

				HttpRequest request = requestFactory.buildGetRequest(url);
				HttpResponse httpResponse = request.execute();
				DirectionsResult directionsResult = httpResponse.parseAs(DirectionsResult.class);
				String encodedPoints = directionsResult.routes.get(0).overviewPolyLine.points;
				latLngs = PolyUtil.decode(encodedPoints);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			return null;
			}
*/
			// Instantiates a new Polyline object and adds points to define a rectangle
			/*PolylineOptions rectOptions = new PolylineOptions()
				.add(new LatLng(mLocationClient.getLastLocation().getLatitude(),mLocationClient.getLastLocation().getLongitude()))
			    .add(new LatLng(mLocationClient.getLastLocation().getLatitude()+1,mLocationClient.getLastLocation().getLongitude()+1))
			    .add(new LatLng(mLocationClient.getLastLocation().getLatitude(),mLocationClient.getLastLocation().getLongitude()));

			// Get back the mutable Polyline
			Polyline polyline = mMap.addPolyline(rectOptions);
			Context context = getApplicationContext();
			CharSequence text = "polylineOption!";
			int duration = Toast.LENGTH_SHORT;
			Toast toast = Toast.makeText(context, text, duration);
			toast.show();*/
		} catch (Exception e){
			Context context = getApplicationContext();
			CharSequence text = "Null Pointeur Exeption!";
			int duration = Toast.LENGTH_SHORT;
			Toast toast = Toast.makeText(context, text, duration);
			toast.show();
		}
	}

	/**
	 * Callback called when disconnected from GCore. Implementation of
	 * {@link ConnectionCallbacks}.
	 */
	@Override
	public void onDisconnected() {
		// Do nothing
	}

	/**
	 * Implementation of {@link OnConnectionFailedListener}.
	 */
	@Override
	public void onConnectionFailed(ConnectionResult result) {
		// Do nothing
	}

	@Override
	public boolean onMyLocationButtonClick() {
		// Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT)
		// .show();

		// Return false so that we don't consume the event and the default
		// behavior still occurs
		// (the camera animates to the user's current position).
		return false;
	}

	@Override
	public void activate(OnLocationChangedListener arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void deactivate() {
		// TODO Auto-generated method stub

	}
}
